package com.ws.haungjia.config;


import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

//初始化web容器 替代web.xml
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("onStartupMyWebApplicationInitializer");
        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringMvcConfig.class);

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");


        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", filter);
        encodingFilter.addMappingForUrlPatterns(null, false, "/*");

        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }
}
